<template>
  <el-container style="height: 100%">
    <el-header style="background-color: aliceblue; height: 80px; font-size: 20px">
      <el-row type="flex" justify="space-between">
        <el-col :span="4">
          <el-button type="text" style="font-size: 30px; color: black">
            <i class="el-icon-s-home" style="font-size: 40px; color: black"></i>
            智慧养老
            <span class="material-icons">elderly</span>
          </el-button>
        </el-col>
        <el-col :span="16">
          <el-menu
            style="margin-top: 10px; background-color: aliceblue"
            mode="horizontal"
            text-color="black"
            active-text-color="blue"
          >
            <el-menu-item
              :index="menus.id + ''"
              v-for="menus in menuData"
              :key="menus.id"
              @click="selectMenu(menus.id)"
            >{{ menus.name }}</el-menu-item>
          </el-menu>
        </el-col>
        <el-col :span="2" style="margin-top: 20px;">
          <el-dropdown>
            <el-button type="info" icon="el-icon-message" circle class="el-dropdown-link"></el-button>
            <!-- 聊天室图标按钮 -->
            <el-button type="text" @click="goToChatRoom">
              <i class="el-icon-chat-dot-round" style="font-size: 40px; color: black"></i>
            </el-button>
            <el-dropdown-menu class="vertical-dropdown" popper-class="vertical-dropdown" >
              <template v-if="messages.length > 0">
                <div class="message-container">
                  <el-dropdown-item
                    style="color: red;width:250px"
                    class-name="message-item"
                    v-for="message in messages"
                    :key="message.id"
                  >{{ message }}</el-dropdown-item>
                </div>
              </template>
              <template v-else>
                <el-dropdown-item>没有任何消息</el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
        <el-col :span="2" style="text-align: right; margin-top: 10px">
          <el-dropdown trigger="click" class="user-profile-dropdown">
            <el-button type="text" class="dropdown-toggle">
              <el-avatar :src="dateInfo.icon" size="medium"></el-avatar>
              <span>{{ dateInfo.name }}</span>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="goToHomePage">主页</el-dropdown-item>
              <el-dropdown-item @click.native="goToSettings">修改密码</el-dropdown-item>
              <el-dropdown-item divided @click.native="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-header>
    <el-container>
      <el-aside
        width="230px"
        style="
          background-color: rgb(84, 92, 100);
          height: 100%;
          overflow: auto;
          scrollbar-width: none;
          -ms-overflow-style: none;
        "
        v-if="selectedMenu"
      >
        <el-menu router background-color="#545c64" text-color="#fff" active-text-color="yellow">
          <el-submenu
            :index="child.id + ''"
            v-for="child in selectedMenu.childrenMenu"
            :key="child.id"
          >
            <template slot="title">
              <i :class="child.icon"></i>
              <span>{{ child.name }}</span>
            </template>
            <el-menu-item
              :index="grandchild.link"
              v-for="grandchild in child.childrenMenu"
              :key="grandchild.id"
            >
              <template slot="title">{{ grandchild.name }}</template>
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </el-aside>
      <el-main style="background-color: azure">
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
export default {
  data() {
    return {
      userId: "",
      dateInfo: {
        icon: ""
      },
      menuData: [],
      selectedMenu: null, // 这将存储用户选择的一级菜单项
      messages: [],
      isDropdownVisible: false
    };
  },
  methods: {
    goToChatRoom() {
      // 跳转到聊天室页面的逻辑，这里使用了vue-router
      // 请确保已有定义这个路由
      this.$router.push("/chat").catch(err => {
        if (err.name !== "NavigationDuplicated") {
          // 如果错误不是 NavigationDuplicated，
          // 则可能是其他的错误，您可以处理或抛出它
          throw err;
        }
        // 如果是 NavigationDuplicated 错误，不做任何处理
      });
    },
    queryById() {
      this.$axios.get("api/employee/queryById/" + this.userId).then(res => {
        if (res.data.code == 200) {
          this.dateInfo = res.data.data;
        }
      });
    },

    selectMenu(id) {
      this.selectedMenu = this.menuData.find(menus => menus.id == id);
    },
    queryUserMenu() {
      //查询用的菜单信息
      this.$axios.get("api/menu/queryUserMenu").then(res => {
        if (res.data.code == 200) {
          this.menuData = res.data.data;
          this.selectMenu(1);
        } else if (res.data.code == 2002) {
          this.$message("无权限访问");
        }
      });
    },
    goToHomePage() {
      // 如果我们已经在主页，则没有必要再次导航
      if (this.$route.path === "/homeIndex") {
        return;
      }
      this.$router.push("/homeIndex").catch(err => {
        // 忽略重复导航产生的错误（例如：我们已经处于/home目录）
        if (err.name !== "NavigationDuplicated") throw err;
      });
    },
    goToSettings() {
      // 导航到设置页逻辑
      // 检查是否已经在/home页面，避免重复导航
      if (this.$route.path !== "/updatePW") {
        //路由到首页
        this.$router.push("/updatePW");
      }
    },
    logout() {
      // 导航到设置页逻辑
      this.$router.push("/login");
    },
    toggleDropdown() {
      this.isDropdownVisible = !this.isDropdownVisible; // 切换下拉菜单的显示状态
    },
    setupWebSocket() {
      // 创建WebSocket连接
      const socket = new WebSocket("ws://localhost/ws/expirations");
      // 监听连接建立事件
      socket.onopen = function(event) {
        console.log("WebSocket连接已建立。");
        // 前端发送消息
        socket.send("Hello from client!");
      };
      // 监听接收消息事件
      socket.onmessage = event => {
        const message = event.data;
        console.log(message);
        this.messages.push(message); // 将接收到的消息添加到数组中
      };
      // 监听连接关闭事件
      socket.onclose = function(event) {
        console.log("WebSocket连接已关闭。");
      };
      // 监听连接错误事件
      socket.onerror = function(error) {
        console.error("WebSocket连接发生错误：", error);
      };
    }
  },
  created() {
    this.setupWebSocket();
    this.userId = window.localStorage.getItem("userId");
    this.queryUserMenu();
    this.queryById();
  }
};
</script>

<style scoped>
.message-container {
  display: flex;
  flex-direction: column;
  max-height: 200px;
  overflow-y: auto;
}

.message-container .el-dropdown-item {
  white-space: normal;
}
</style>